package com.alks.function.service.impl.stockdept.pcfactorystockquery;

import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.beanutils.ArrayUtils;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.common.utils.beanutils.StringUtils;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.controller.SdCompanyController;
import com.alks.function.data.dto.stockdept.pcfactorystockwork.DrawActMtlDto;
import com.alks.function.data.dto.stockdept.pcfactorystockwork.DrawDetailDto;
import com.alks.function.data.dto.stockdept.pcfactorystockwork.DrawReMtlDto;
import com.alks.function.data.request.stockdept.pcfactorystockwork.DrawActMtlRequest;
import com.alks.function.data.request.stockdept.pcfactorystockwork.DrawActProRequest;
import com.alks.function.data.request.stockdept.pcfactorystockwork.DrawDetailRequest;
import com.alks.function.data.request.stockdept.pcfactorystockwork.DrawReMtlRequest;
import com.alks.function.data.vo.MtlBaseVo;
import com.alks.function.data.vo.controller.stockdept.HgMtlRelationVo;
import com.alks.function.data.vo.stock.ReDrawVo;
import com.alks.function.mapper.stockdept.pcfactorystockquery.SD_SQ_PcDrawAttachMapper;
import com.alks.function.mapper.stockdept.pcfactorystockquery.SD_SQ_PcDrawDetailMapper;
import com.alks.function.mapper.stockdept.pcfactorystockquery.SD_SQ_PcDrawReplaceMapper;
import com.alks.function.mapper.stockdept.pcfactorystockquery.SD_SQ_PcMtlAccMapper;
import com.alks.function.service.stockdept.pcfactorystockquery.IHgMtlService;
import com.alks.function.service.stockdept.pcfactorystockquery.IReciveMtlService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.alks.entity.data.enums.ResultCodeEnum.*;

@Service
@Slf4j
@RequiredArgsConstructor
public class ReciveMtlServiceImpl extends ServiceImpl<SD_SQ_PcDrawDetailMapper, PcDrawDetail> implements IReciveMtlService {
    private final SD_SQ_PcDrawDetailMapper detailMapper;
    private final SD_SQ_PcDrawReplaceMapper replaceMapper;
    private final SD_SQ_PcDrawAttachMapper attachMapper;
    private final SD_SQ_PcMtlAccMapper accMapper;
    private final IHgMtlService hgMtlService;
    private final SdCompanyController company;

    @Value("${spring.profiles.active}")
    private String env;

    @Override
    @AutoPageAop
    public ResponseInfo getDrawDetailQuery(DrawDetailRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        /*获取数据*/
        List<DrawDetailDto> dtos = detailMapper.getDrawDetailQuery(request, companyId);
        Page<DrawDetailDto> page = (Page<DrawDetailDto>) dtos;
        // 补充海关数据
        if ("test".equals(env)||"rypro".equals(env)){
            List<HgMtlRelation> relationList = new ArrayList<>();
            for (DrawDetailDto dto : dtos) {
                HgMtlRelation mtlRelation = new HgMtlRelation().setMtlNo(dto.getMtlNo())
                        .setMtlName(dto.getMtlName())
                        .setMtlSpec(dto.getMtlSpec())
                        .setMtlColor(dto.getMtlColor())
                        .setMtlUnit(dto.getMtlUnit());
                relationList.add(mtlRelation);
            }
            // 获取数据
            Map<String, HgMtlRelationVo> hgMtlRelationMap = hgMtlService.detailMapQueryByMtlList(relationList);
            if (ArrayUtils.isNotEmpty(hgMtlRelationMap)){
                for (DrawDetailDto dto : dtos) {
                    String key = Arrays.asList(
                            Optional.ofNullable(dto.getMtlNo()).orElse(""),
                            Optional.ofNullable(dto.getMtlName()).orElse(""),
                            Optional.ofNullable(dto.getMtlColor()).orElse(""),
                            Optional.ofNullable(dto.getMtlSpec()).orElse(""),
                            Optional.ofNullable(dto.getMtlUnit()).orElse("")
                    ).toString();
                    HgMtlRelationVo matched = hgMtlRelationMap.get(key);
                    if (matched != null) {
                        dto.setMtlNoHg(matched.getMtlNoHg());
                        dto.setMtlNameEng(matched.getMtlNameEng());
                    }
                }
            }
        }
        /*封装数据*/
        Map<String, Object> map = new HashMap<>(2);
        map.put("dtos", dtos);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getDrawActQuery(Integer id) {
        String companyId = UserIdThread.get().getCompanyId();
        /*获取数据*/
        LambdaQueryWrapper<PcDrawAttach> wrapper = new LambdaQueryWrapper<PcDrawAttach>()
                .select(PcDrawAttach::getActQty, PcDrawAttach::getSlipDate)
                .eq(PcDrawAttach::getDetailId,id)
                .eq(PcDrawAttach::getCompanyId, companyId)
                .orderByDesc(PcDrawAttach::getSlipDate);
        List<PcDrawAttach> attaches = attachMapper.selectList(wrapper);
        /*提取数据*/
        List<Map<String, Object>> dtos = attaches.stream().map(a -> {
            if (a == null || BeanUtil.allIsEmpty(a)) {
                return new HashMap<String, Object>(0);
            }
            Map<String, Object> map = new HashMap<>(2);
            map.put("actQty", a.getActQty() == null ? 0 : a.getActQty());
            map.put("slipDate", a.getSlipDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            return map;
        }).collect(Collectors.toList());
        /*求和*/
        Double sum = attaches.stream()
                .filter(attach -> Optional.ofNullable(attach).map(PcDrawAttach::getActQty).isPresent())
                .mapToDouble(PcDrawAttach::getActQty).sum();
        /*封装数据*/
        Map<String, Object> map = new HashMap<>(2);
        map.put("dtos", dtos);
        map.put("sum", sum);
        return ResponseInfo.ok(map);
    }

    @Override
    @AutoPageAop
    public ResponseInfo getDrawReMtlQuery(DrawReMtlRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        /*获取数据*/
        LambdaQueryWrapper<PcMtlAcc> wrapper = new LambdaQueryWrapper<PcMtlAcc>()
                .select(PcMtlAcc::getMtlNo, PcMtlAcc::getMtlName, PcMtlAcc::getMtlColor,
                        PcMtlAcc::getMtlUnit, PcMtlAcc::getMtlSpec, PcMtlAcc::getStkQty)
                .like(!request.getMtlName().isEmpty(), PcMtlAcc::getMtlName, request.getMtlName())
                .like(!request.getMtlTypeNo().isEmpty(), PcMtlAcc::getMtlNo, request.getMtlTypeNo())
                .eq(PcMtlAcc::getCompanyId, companyId)
                .orderByAsc(PcMtlAcc::getMtlNo);
        List<PcMtlAcc> pcMtlAccs = accMapper.selectList(wrapper);
        /*提取数据*/
        List<DrawReMtlDto> dtos = BeanUtil.copyList(pcMtlAccs, DrawReMtlDto.class);
        Page<PcMtlAcc> page = (Page<PcMtlAcc>) pcMtlAccs;
        /*封装数据*/
        Map<String, Object> map = new HashMap<>(2);
        map.put("dtos", dtos);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    @Transactional
    public ResponseInfo DrawActPro(List<DrawActProRequest> request, Integer flag) {
        String companyId = UserIdThread.get().getCompanyId();
        /*数据校验*/
        long count = request.stream().filter(Objects::nonNull).filter(a -> a.getActQty()==null || a.getActQty()<=0).count();
        if (count > 0){
            return ResponseInfo.error("实发数量不能小于0");
        }

        List<PcDrawDetail> detaiList = detailMapper.actDataQuery(request, companyId);
        for (PcDrawDetail detail : detaiList) {
            if (Objects.equals(detail.getCancelFlag(), "Y")) {
                return ResponseInfo.error("领料单已取消，不能实发");
            }
        }

        Map<String, PcDrawDetail> aggregatedMap = new HashMap<>();
        for (PcDrawDetail detail : detaiList) {
            // 创建一个唯一键来标识相同的物料
            String key = detail.getMtlNo() + "|" + detail.getMtlName() + "|" +
                    (detail.getMtlColor() != null ? detail.getMtlColor() : "") + "|" +
                    (detail.getMtlSpec() != null ? detail.getMtlSpec() : "") + "|" +
                    detail.getMtlUnit();

            if (aggregatedMap.containsKey(key)) {
                // 如果已存在相同物料，则累加 actQty
                PcDrawDetail existing = aggregatedMap.get(key);
                existing.setActQty(existing.getActQty()+detail.getActQty());
            } else {
                // 如果是新物料，则放入 map 中
                // 需要创建新的对象，避免修改原始列表中的对象
                PcDrawDetail newDetail = new PcDrawDetail();
                newDetail.setMtlNo(detail.getMtlNo());
                newDetail.setMtlName(detail.getMtlName());
                newDetail.setMtlColor(detail.getMtlColor());
                newDetail.setMtlSpec(detail.getMtlSpec());
                newDetail.setMtlUnit(detail.getMtlUnit());
                newDetail.setActQty(detail.getActQty());
                aggregatedMap.put(key, newDetail);
            }
        }
        List<PcDrawDetail> aggregatedList = new ArrayList<>(aggregatedMap.values());

        List<String> mtlList = accMapper.queryStkShort(aggregatedList, companyId);
        if (ArrayUtils.isNoEmpyt(mtlList)) {
            throw new ServiceErrorException("库存不足 物料：" + mtlList.get(0));
        }

        /*更新物料替换数据*/
        replaceMapper.actUp(detaiList, companyId);

        /*新增领料数据*/
        for (PcDrawDetail detail : detaiList) {
            PcDrawAttach attach = new PcDrawAttach()
                    .setCompanyId(companyId)
                    .setStockNo(detail.getStockNo())
                    .setSlipNo(detail.getSlipNo())
                    .setLotNo(detail.getLotNo())
                    .setMtlNo(detail.getMtlNo())
                    .setMtlName(detail.getMtlName())
                    .setMtlColor(detail.getMtlColor())
                    .setMtlSpec(detail.getMtlSpec())
                    .setMtlUnit(detail.getMtlUnit())
                    .setDeptNo(detail.getDeptNo())
                    .setDeptName(detail.getDeptName())
                    .setActQty(detail.getActQty())
                    .setSlipDate(detail.getSlipDate())
                    .setSysDate(LocalDateTime.now())
                    .setSysUser(UserIdThread.get().getUserName())
                    .setDetailId(detail.getId());
            attachMapper.insert(attach);
        }
        /*更新主表数据*/
        detailMapper.DrawActProUp(request, companyId);
        /*更新材料用量表数据*/
        accMapper.DrawActProUp(detaiList);
        return ResponseInfo.ok("实发完成");
    }

    @Override
    @AutoPageAop
    public ResponseInfo getDrawActMtlQuery(DrawActMtlRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        /*查找数据*/
        LambdaQueryWrapper<PcDrawReplace> wrapper = new LambdaQueryWrapper<PcDrawReplace>()
                .select()
                .like(!request.getMtlName1().isEmpty(), PcDrawReplace::getMtlName, request.getMtlName1())
                .like(!request.getMtlName2().isEmpty(), PcDrawReplace::getMtlName2, request.getMtlName2())
                .like(!request.getSlipNo().isEmpty(), PcDrawReplace::getSlipNo, request.getSlipNo())
                .eq(PcDrawReplace::getCompanyId, companyId)
                .orderByDesc(PcDrawReplace::getSlipNo);
        List<PcDrawReplace> pcDrawReplaces = replaceMapper.selectList(wrapper);
        /*提取数据*/
        List<DrawActMtlDto> dtos = BeanUtil.copyList(pcDrawReplaces, DrawActMtlDto.class);
        Page<PcDrawReplace> page = (Page<PcDrawReplace>) pcDrawReplaces;
        /*封装数据*/
        Map<String, Object> map = new HashMap<>();
        map.put("dtos", dtos);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo drawDetailCancel(String slipNo, String mtlNo, String lotNo) {
        String companyId = UserIdThread.get().getCompanyId();
        /*查找数据*/
        PcDrawDetail one = lambdaQuery()
                .eq(PcDrawDetail::getMtlNo, mtlNo)
                .eq(PcDrawDetail::getLotNo, lotNo)
                .eq(PcDrawDetail::getCompanyId, companyId)
                .eq(PcDrawDetail::getSlipNo, slipNo).one();
        /*判定是否存在实发*/
        if (one == null || BeanUtil.allIsEmpty(one)) {
            log.error("请求方法：drawDetailCancel\n错误原因：未找到数据\n请求参数：slipNo:{} 、mtlNo:{}",
                    slipNo, mtlNo);
            return ResponseInfo.error("数据异常，请联系后台管理", DATA_IS_EMPTY.getCode());
        }
        if (!(one.getActQty() == null || one.getActQty() == 0)) {
            return ResponseInfo.error("存在实发记录，不能取消");
        }
        /*修改数据*/
        lambdaUpdate().eq(PcDrawDetail::getMtlNo, mtlNo)
                .eq(PcDrawDetail::getSlipNo, slipNo)
                .eq(PcDrawDetail::getLotNo, lotNo)
                .eq(PcDrawDetail::getCompanyId, companyId)
                .set(PcDrawDetail::getCancelDate, LocalDateTime.now())
                .set(PcDrawDetail::getCancelFlag, "Y")
                .set(PcDrawDetail::getCancelUser, UserIdThread.get().getUserName())
                .update();
        return ResponseInfo.ok("取消成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void drawRollBack() {
        String companyId = UserIdThread.get().getCompanyId();
        /*获取需要删除的订单*/
        List<ReDrawVo> voList = detailMapper.getErrSlipDate(companyId);
        /*相同实发直接删除*/
        List<ReDrawVo> eqList = voList.stream()
                .filter(a -> a.getCurrentQty().equals(a.getNextQty()))
                .collect(Collectors.toList());
        /*删除订单*/
        for (ReDrawVo vo : eqList) {
            LambdaQueryWrapper<PcDrawDetail> detailWrapper = new LambdaQueryWrapper<PcDrawDetail>()
                    .eq(PcDrawDetail::getCompanyId, companyId)
                    .eq(PcDrawDetail::getSlipNo, vo.getNextSlipNo())
                    .eq(PcDrawDetail::getMtlNo, vo.getMtlNo())
                    .eq(PcDrawDetail::getLotNo, vo.getLotNo());
            /*删除明细*/
            detailMapper.delete(detailWrapper);
            LambdaQueryWrapper<PcDrawAttach> attachWrapper = new LambdaQueryWrapper<PcDrawAttach>()
                    .eq(PcDrawAttach::getCompanyId, companyId)
                    .eq(PcDrawAttach::getSlipNo, vo.getNextSlipNo())
                    .eq(PcDrawAttach::getMtlNo, vo.getMtlNo())
                    .eq(PcDrawAttach::getLotNo, vo.getLotNo());
            attachMapper.delete(attachWrapper);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void drawMtlReplace(Integer id, MtlBaseVo mtl) {
        String companyId = UserIdThread.get().getCompanyId();
        /*判断是否重复*/
        PcDrawDetail detail = detailMapper.selectById(id);
        String newMtl = detail.getMtlNo()+detail.getMtlName()+detail.getMtlColor()+detail.getMtlSpec()+detail.getMtlUnit();
        String oldMtl = mtl.getMtlNo()+mtl.getMtlName()+mtl.getMtlColor()+mtl.getMtlSpec()+mtl.getMtlUnit();
        if (newMtl.replaceAll("\\s", "").equals(oldMtl.replaceAll("\\s", ""))){
            throw new ServiceErrorException("替代后材料和原材料相同");
        }
        /*判断物料是否存在*/
        LambdaQueryWrapper<PcMtlAcc> accWrapper = new LambdaQueryWrapper<PcMtlAcc>()
                .eq(PcMtlAcc::getMtlNo, mtl.getMtlNo())
                .eq(PcMtlAcc::getMtlName, mtl.getMtlName())
                .eq(StringUtil.isNotBlank(mtl.getMtlColor()),PcMtlAcc::getMtlColor, mtl.getMtlColor())
                .isNull(StringUtil.isBlank(mtl.getMtlColor()),PcMtlAcc::getMtlColor)
                .eq(StringUtil.isNotBlank(mtl.getMtlSpec()),PcMtlAcc::getMtlSpec, mtl.getMtlSpec())
                .isNull(StringUtil.isBlank(mtl.getMtlSpec()),PcMtlAcc::getMtlSpec)
                .eq(StringUtil.isNotBlank(mtl.getMtlUnit()),PcMtlAcc::getMtlUnit, mtl.getMtlUnit())
                .isNull(StringUtil.isBlank(mtl.getMtlUnit()),PcMtlAcc::getMtlUnit)
                .eq(PcMtlAcc::getCompanyId, companyId);
        accMapper.selectCount(accWrapper);
        if (accMapper.selectCount(accWrapper) == 0) {
            throw new ServiceErrorException("物料不存在");
        }
        /*写入材料替代数据*/
        LambdaUpdateWrapper<PcDrawDetail> wrapper = new LambdaUpdateWrapper<PcDrawDetail>()
                .set(PcDrawDetail::getMtlNo2, mtl.getMtlNo())
                .eq(PcDrawDetail::getId, id)
                .eq(PcDrawDetail::getCompanyId, companyId);
        detailMapper.update(null, wrapper);
        if (StringUtils.isBlank(detail.getMtlNo2())) {
            /*首次替代则写入材料替代明细*/
            PcDrawReplace replace = new PcDrawReplace()
                    .setCompanyId(companyId)
                    .setStockNo("X1")
                    .setSlipType("I")
                    .setSlipType2("O")
                    .setOutType("领料单")
                    .setMtlNo(detail.getMtlNo())
                    .setMtlName(detail.getMtlName())
                    .setMtlColor(detail.getMtlColor())
                    .setMtlSpec(detail.getMtlSpec())
                    .setMtlUnit(detail.getMtlUnit())
                    .setMtlNo2(mtl.getMtlNo())
                    .setMtlName2(mtl.getMtlName())
                    .setMtlColor2(mtl.getMtlColor())
                    .setMtlSpec2(mtl.getMtlSpec())
                    .setMtlUnit2(mtl.getMtlUnit())
                    .setSlipNo(detail.getSlipNo())
                    .setSysDate(LocalDateTime.now())
                    .setSysUser(UserIdThread.get().getUserName());
            replaceMapper.insert(replace);
        }else{
            /*否则更新替代数据*/
            LambdaUpdateWrapper<PcDrawReplace> replaceWrapper = new LambdaUpdateWrapper<PcDrawReplace>()
                    .set(PcDrawReplace::getMtlNo2, mtl.getMtlNo())
                    .set(PcDrawReplace::getMtlName2, mtl.getMtlName())
                    .set(PcDrawReplace::getMtlColor2, mtl.getMtlColor())
                    .set(PcDrawReplace::getMtlSpec2, mtl.getMtlSpec())
                    .set(PcDrawReplace::getMtlUnit2, mtl.getMtlUnit())
                    .eq(PcDrawReplace::getSlipNo, detail.getSlipNo())
                    .eq(PcDrawReplace::getMtlNo, detail.getMtlNo())
                    .eq(PcDrawReplace::getMtlName, detail.getMtlName())
                    .eq(StringUtil.isNotBlank(detail.getMtlColor()),PcDrawReplace::getMtlColor, detail.getMtlColor())
                    .isNull(StringUtil.isBlank(detail.getMtlColor()),PcDrawReplace::getMtlColor)
                    .eq(StringUtil.isNotBlank(detail.getMtlSpec()),PcDrawReplace::getMtlSpec, detail.getMtlSpec())
                    .isNull(StringUtil.isBlank(detail.getMtlSpec()),PcDrawReplace::getMtlSpec)
                    .eq(StringUtil.isNotBlank(detail.getMtlUnit()),PcDrawReplace::getMtlUnit, detail.getMtlUnit())
                    .isNull(StringUtil.isBlank(detail.getMtlUnit()),PcDrawReplace::getMtlUnit)
                    .eq(PcDrawReplace::getCompanyId, companyId);
            replaceMapper.update(null, replaceWrapper);
        }
    }

    @Override
    public MtlBaseVo drawReplaceMtlQuery(Integer id) {
        String companyId = UserIdThread.get().getCompanyId();
        /*获取主表物料数据*/
        PcDrawDetail detail = detailMapper.selectById(id);
        if (!companyId.equals(detail.getCompanyId())||StringUtils.isBlank(detail.getMtlNo2())){
            return new MtlBaseVo();
        }

        /*通过主表数据获取替换后材料数据*/
        LambdaQueryWrapper<PcDrawReplace> replaceWrapper = new LambdaQueryWrapper<PcDrawReplace>()
                .eq(PcDrawReplace::getSlipNo, detail.getSlipNo())
                .eq(PcDrawReplace::getMtlNo, detail.getMtlNo())
                .eq(PcDrawReplace::getMtlName, detail.getMtlName())
                .eq(StringUtil.isNotBlank(detail.getMtlColor()),PcDrawReplace::getMtlColor, detail.getMtlColor())
                .isNull(StringUtil.isBlank(detail.getMtlColor()),PcDrawReplace::getMtlColor)
                .eq(StringUtil.isNotBlank(detail.getMtlSpec()),PcDrawReplace::getMtlSpec, detail.getMtlSpec())
                .isNull(StringUtil.isBlank(detail.getMtlSpec()),PcDrawReplace::getMtlSpec)
                .eq(StringUtil.isNotBlank(detail.getMtlUnit()),PcDrawReplace::getMtlUnit, detail.getMtlUnit())
                .isNull(StringUtil.isBlank(detail.getMtlUnit()),PcDrawReplace::getMtlUnit)
                .eq(PcDrawReplace::getCompanyId, companyId);
        List<PcDrawReplace> replace = replaceMapper.selectList(replaceWrapper);
        if (ArrayUtils.isEmpyt(replace)){
            return new MtlBaseVo();
        }
        MtlBaseVo mtlBaseVo = new MtlBaseVo()
                .setMtlNo(replace.get(0).getMtlNo2())
                .setMtlName(replace.get(0).getMtlName2())
                .setMtlColor(replace.get(0).getMtlColor2())
                .setMtlSpec(replace.get(0).getMtlSpec2())
                .setMtlUnit(replace.get(0).getMtlUnit2());

        /*补充库存数据*/
        LambdaQueryWrapper<PcMtlAcc> accWrapper = new LambdaQueryWrapper<PcMtlAcc>()
                .select(PcMtlAcc::getStkQty)
                .eq(PcMtlAcc::getMtlNo, replace.get(0).getMtlNo2())
                .eq(PcMtlAcc::getMtlName, replace.get(0).getMtlName2())
                .eq(StringUtil.isNotBlank(replace.get(0).getMtlColor2()),PcMtlAcc::getMtlColor, replace.get(0).getMtlColor2())
                .isNull(StringUtil.isBlank(replace.get(0).getMtlColor2()),PcMtlAcc::getMtlColor)
                .eq(StringUtil.isNotBlank(replace.get(0).getMtlSpec2()),PcMtlAcc::getMtlSpec, replace.get(0).getMtlSpec2())
                .isNull(StringUtil.isBlank(replace.get(0).getMtlSpec2()),PcMtlAcc::getMtlSpec)
                .eq(StringUtil.isNotBlank(replace.get(0).getMtlUnit2()),PcMtlAcc::getMtlUnit, replace.get(0).getMtlUnit2())
                .isNull(StringUtil.isBlank(replace.get(0).getMtlUnit2()),PcMtlAcc::getMtlUnit)
                .eq(PcMtlAcc::getCompanyId, companyId);
        PcMtlAcc acc = accMapper.selectOne(accWrapper);
        if (acc != null) {
            mtlBaseVo.setStkQty(acc.getStkQty());
        }
        return mtlBaseVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void drawReplaceDel(Integer id) {
        String companyId = UserIdThread.get().getCompanyId();
        /*获取基础数据*/
        LambdaUpdateWrapper<PcDrawDetail> detailWrapper = new LambdaUpdateWrapper<PcDrawDetail>()
                .eq(PcDrawDetail::getId, id)
                .eq(PcDrawDetail::getCompanyId, companyId);
        PcDrawDetail detail = detailMapper.selectOne(detailWrapper);
        if (detail == null){
            return;
        }

        /*删除替代表数据*/
        LambdaQueryWrapper<PcDrawReplace> replaceWrapper = new LambdaQueryWrapper<PcDrawReplace>()
                .eq(PcDrawReplace::getSlipNo, detail.getSlipNo())
                .eq(PcDrawReplace::getMtlNo, detail.getMtlNo())
                .eq(PcDrawReplace::getMtlName, detail.getMtlName())
                .eq(StringUtil.isNotBlank(detail.getMtlColor()),PcDrawReplace::getMtlColor, detail.getMtlColor())
                .isNull(StringUtil.isBlank(detail.getMtlColor()),PcDrawReplace::getMtlColor)
                .eq(StringUtil.isNotBlank(detail.getMtlSpec()),PcDrawReplace::getMtlSpec, detail.getMtlSpec())
                .isNull(StringUtil.isBlank(detail.getMtlSpec()),PcDrawReplace::getMtlSpec)
                .eq(StringUtil.isNotBlank(detail.getMtlUnit()),PcDrawReplace::getMtlUnit, detail.getMtlUnit())
                .isNull(StringUtil.isBlank(detail.getMtlUnit()),PcDrawReplace::getMtlUnit)
                .eq(PcDrawReplace::getCompanyId, companyId);
        replaceMapper.delete(replaceWrapper);

        /*更新主表数据*/
        detailWrapper.set(PcDrawDetail::getMtlNo2, null);
        detailMapper.update(null, detailWrapper);
    }

}
